import axios from 'axios'
import store from '@/store'
import router from '@/router'
// import { MessageBox, Message } from 'element-ui'
// import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 设置axios请求的基础的基础地址
  timeout: 5000 // 定义5秒超时
})

// 响应拦截器
service.interceptors.response.use(
  response => {
    console.log('从后端回来的数据', response)
    if (response.data.success === false) {
      return Promise.reject(new Error(response.data.message))
    } else {
      return response.data
    }
  },
  error => {
    // token失效处理
    console.dir(error)
    if (error.response.data.code === 10002) {
      store.dispatch('user/userLogout')
      router.push('/login?return_url=' + router.currentRoute.path)
    }
    return Promise.reject(error)
  }
)

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    // 如果当前存有token,就加在请求头上
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  }
  , error => {
    return Promise.reject(error)
  })

export default service
